import React, {memo, useEffect, useRef, useState} from 'react';
import RegisterStyle from "./RegisterStyle";
import {
  Button,
  Cascader,
  Checkbox,
  ColorPicker,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Select,
  Slider,
  Switch,
  TreeSelect,
  Upload,
  message,
} from "antd";
import type {UploadProps} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import {useNavigate} from "react-router-dom";
import {getSysDictData} from "../../services/sysDictData";
import {addUserApi} from "../../services/user";
import {sendSmsApi} from "../../services/sendSms";

type Props = {};
type userRegisterType = {
  phone: string,
  password: string,
  againPassword: string,
  motto?: string
  nickname?: string,
  cover?: string,
  realname?: string,
  nationalityId?: number,
  nationality?: string,
  introduction?: string,
  birthday?: string,
  otherName?: string,
  verificationCode: number,
}

export default memo(function Register(props: Props) {
  //路由
  const navigate = useNavigate();
  //antd全局提示
  const [messageApi, contextHolder] = message.useMessage();
  const [nationalityList, setNationalityList] = useState([]);
  const [imageUrl, setImageUrl] = useState("");
  //倒计时数字展示
  const [sendSmsCountdown, setSendSmsCountdown] = useState(0);
  //短信验证码
  const [smsCode,setSmsCode] = useState(0);
  //手机号码ref
  const phoneRef:any=useRef();

  const onFinish = (values: userRegisterType) => {
    console.log(values);
    if (imageUrl != null) {
      values.cover = imageUrl;
    }
    if (values.phone.length!==11){
      messageApi.open({
        type: "error",
        content: "手机号码格式不正确"
      });
    } else if (values.password !== values.againPassword) {
      messageApi.open({
        type: "error",
        content: "两次密码不同"
      });
    } else if (values.verificationCode!=smsCode){
      messageApi.open({
        type: "error",
        content: "手机验证码有误"
      });
    } else {
      //开始注册
      addUserApi(values).then((result: any) => {
        console.log(result);
        if (result.data.code === 200) {
          navigate("/login");
          messageApi.open({
            type: "success",
            content: "注册成功"
          });
        } else {
          messageApi.open({
            type: "error",
            content: "注册失败"
          });
        }
      }, (error) => {
        console.log(error);
      });
    }
  };
  //文件上传验证
  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传jpeg 或者 png 格式的文件');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不可超过2MB');
    }
    return isJpgOrPng && isLt2M;
  };

  //文件上传
  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      const result = info.file.response;
      if (result.code === 200) {
        setImageUrl(result.data);
        message.open({
          type: "success",
          content: "上传头像成功"
        });
      } else {
        message.open({
          type: "error",
          content: "上传头像失败"
        });
      }
    }
  };

  //页面加载时，请求接口方法
  useEffect(() => {
    //获取字典
    //根据国籍查询
    getSysDictData({dictType: "area_type"}).then((result: any) => {
      console.log(result);
      setNationalityList(result.data.data.data);
    }, (error) => {
      console.log(error);
    });
    // sendSmsBtn()
  }, []);


  //发送验证码按钮事件
  function sendSmsBtn() {
    const phone:string=phoneRef.current.input.value;
    if (phone.length===11){
      let aa = 60;
      setSendSmsCountdown(aa);
      sendSmsApi(phone).then((result:any)=>{
        console.log(result);
        if (result.data.code===200){
          messageApi.open({
            type:"success",
            content:"手机验证码发送成功"
          });
          //给变量赋值
          setSmsCode(result.data.data.code);
        }
      },(error)=>{
        console.log(error);
      });
      let timer = setInterval(() => {
        aa--;
        setSendSmsCountdown(aa);
        if (aa<1){//清除定时器
          clearInterval(timer);
        }
      }, 1000);
    }else{
      messageApi.open({
        type:"error",
        content:"手机号码有误"
      });
    }
  }

  return (
    <RegisterStyle>
      {/*<button onClick={()=>{*/}
      {/*  setSendSmsCountdown(sendSmsCountdown+1);*/}
      {/*  console.log(sendSmsCountdown)*/}
      {/*}}>哈哈</button>*/}
      {contextHolder}
      <div className="register-box">
        <div className="register-left-box"></div>
        <div className="register-right-box">
          <div className="register-form-box">
            <h1>注册</h1>
            <Form
              labelCol={{span: 7}}
              wrapperCol={{span: 14}}
              layout="horizontal"
              style={{maxWidth: 600}}
              autoComplete="off"
              onFinish={onFinish}
            >
              <Form.Item
                label="手机号码"
                name="phone"
                rules={[{required: true, message: '请输入您的手机号码'}]}
              >
                {/*@ts-ignore*/}
                <Input ref={phoneRef} />
              </Form.Item>
              <Form.Item
                label="账号密码"
                name="password"
                rules={[{required: true, message: '请输入您的账号密码'}]}
              >
                <Input.Password style={{background: "#ffffff"}}/>
              </Form.Item>

              <Form.Item
                label="确认密码"
                name="againPassword"
                rules={[{required: true, message: '请输入您的账号密码'}]}
              >
                <Input.Password style={{background: "#ffffff"}}/>
              </Form.Item>

              <Form.Item
                label="个性签名"
                name="motto"
              >
                <Input/>
              </Form.Item>

              <Form.Item
                label="昵称"
                name="nickname"
              >
                <Input/>
              </Form.Item>

              <Form.Item
                label="头像"
                name="cover"
              >
                <Upload
                  beforeUpload={beforeUpload}
                  action="http://localhost:8081/upload/file"
                  listType="picture-circle"
                  onChange={handleChange}
                >
                  <button style={{border: 0, background: 'none'}} type="button">
                    <PlusOutlined/>
                    <div style={{marginTop: 8}}>上传头像</div>
                  </button>
                </Upload>
              </Form.Item>

              <Form.Item
                label="真实姓名"
                name="realname"
              >
                <Input/>
              </Form.Item>

              <Form.Item
                label="国籍"
                name="nationalityId"
              >
                <Select style={{background: "#ffffff"}}>
                  {
                    nationalityList.map((item: any) => {
                      return (
                        <Select.Option key={item.sysDictDataId} value={item.dictValue}>{item.dictLabel}</Select.Option>)
                    })
                  }
                </Select>
              </Form.Item>

              <Form.Item
                label="生日"
              >
                <DatePicker/>
              </Form.Item>

              <Form.Item
                label="验证码"
                name="verificationCode"
                rules={[{required: true, message: '请输入您的短信验证码'}]}
              >
                <div style={{display: "flex"}}>
                  <Input/>
                  <Button disabled={sendSmsCountdown>0}
                          onClick={sendSmsBtn}>发送验证码 {sendSmsCountdown<1?'':`(${sendSmsCountdown})`}</Button>
                </div>
              </Form.Item>

              <Form.Item wrapperCol={{offset: 8, span: 16}}>
                <Button size={"large"} className="antd-btn public-btn" type="primary" htmlType="submit">
                  注册
                </Button>
                <Button size={"large"}
                        className="antd-btn public-btn public-background-transparent"
                        onClick={() => {
                          navigate("/login")
                        }}
                >
                  已有账号?前往登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </RegisterStyle>
  );
});
